package cn.edu.swu.book;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

public class BookService {


    private BookRepo repo;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");


    public BookService(){

    }

    public List<Book> getAll() throws SQLException, ClassNotFoundException {
        return this.repo.getAllBooks();
    }

    public void save(String name,String author,double price,String memo,String publish) throws SQLException {
        Book book = new Book();
        book.setName(name);
        book.setAuthor(author);
        book.setPrice(price);
        book.setMemo(memo);
        try {
            book.setPublish(simpleDateFormat.parse(publish));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        this.repo.save(book);
    }

    public void deleteById(int id) throws SQLException {
        this.repo.deleteById(id);
    }

    public Book getById(int id) throws SQLException {
        return this.repo.getById(id);
    }


    public void update(int id,String name,String author,double price,String memo,String publish) throws SQLException {
        Book book = new Book();
        book.setId(id);
        book.setName(name);
        book.setAuthor(author);
        book.setPrice(price);
        book.setMemo(memo);
        try {
            book.setPublish(simpleDateFormat.parse(publish));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        this.repo.update(book);
    }

    public List<Book> search(String key) throws SQLException {
        return this.repo.search(key);
    }


    
    public void setRepo(BookRepo repo){
        this.repo = repo;
    }
}
